package com.dy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dy.common.R;
import com.dy.entity.ShoppingCart;
import com.dy.service.ShoppingCartService;
import com.dy.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * ClassName:ShoppingCart
 * Package:com.dy.controller
 * Description:
 *
 * @Date:2022/8/6 14:05
 * @Author:dy
 */
@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;


    /**
     * @Author dy
     * @Description:  用户购物车 添加商品
     */
    @Transactional
    @PostMapping("/add")
    public R<ShoppingCart> addShoppingCart(@RequestBody ShoppingCart shoppingCart){
        return shoppingCartService.addShoppingCart(shoppingCart);
    }

    /**
     * @Author dy
     * @Description: 返回用户的全部购物车数据
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list(){
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<ShoppingCart>();
        queryWrapper.eq(ShoppingCart::getUserId,CurrentHolder.getCurrent());
        List<ShoppingCart> list = shoppingCartService.list();
        return R.success(list);
    }

    /**
     * @date 2022/8/6 15:17
     * @Description: 清空用户购物车
     */
    @DeleteMapping("/clean")
    @Transactional
    public R<String> clean(){
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<ShoppingCart>();
        queryWrapper.eq(ShoppingCart::getUserId,CurrentHolder.getCurrent());
        shoppingCartService.remove(queryWrapper);
        return R.success("清空购物车成功");
    }


    @PostMapping("/sub")
    @Transactional
    public R<ShoppingCart> sub(@RequestBody ShoppingCart shoppingCart){
        if(shoppingCart.getId() != null){
            ShoppingCart byId = shoppingCartService.getById(shoppingCart.getId());
            Integer number = byId.getNumber();
            if(number > 1){
                //商品数量 -1
                byId.setNumber(number - 1);
                shoppingCartService.updateById(byId);
                shoppingCart = byId;
            }else{
                //商品数量只有1， 删除数据
                shoppingCartService.removeById(shoppingCart.getId());
            }
            return R.success(shoppingCart);
        }
        log.error("购物车，减商品错误。");
        return R.error("错误");
    }
}
